<template>
    <div>
      <div>
        <b>配置更新</b>
      </div>
      <Table :columns="tableFieldCol" style="margin-top:10px"
      :data="tableData" :border="tableConfig.border"
      :stripe="tableConfig.stripe" :size="tableConfig.size" :no-data-text="tableConfig.noDataText"
      >
        <template slot-scope="{ row }" v-for="(val, key) in slotConfig" :slot="key">
          <div v-html="createTableTem(val, row)" :key="key"></div>
        </template>
      </Table>
      <div style="margin-top:10px;text-align:left">
        <div style="margin-top:10px;">
          <FIELDATTR :fields="tableCols" :slotAttr="slotConfig" @thChange="thChange"/>
        </div>
        <div style="margin-top:10px;" class="tips">
          <span>表头字段可自定义，自定义字段不与表单内字段同步</span>
        </div>
        <div style="margin-top:10px;" class="tips">
          <a @click="saveThConfig">保存表头配置</a>
          <a @click="resetTH">重置表头字段</a>
        </div>
      </div>
      <div style="margin-top:10px;text-align:left">
        <div>
          <b>表格部分配置</b>
        </div>
        <div style="margin-top:10px;display:flex;align-items: center;justify-content: space-evenly;">
          <div>
            <div>
              <span>表格边框</span>
              <SwitchIview v-model="tableConfig.border"/>
            </div>
            <div style="margin-top:10px">
              <span>斑马线</span>
              <SwitchIview v-model="tableConfig.stripe"/>
            </div>
          </div>
          <div>
            <span>表格大小</span><br>
            <Select v-model="tableConfig.size" style="margin-top:10px;">
              <Option value="default">默认</Option>
              <Option value="large">大尺寸</Option>
              <Option value="small">小尺寸</Option>
            </Select>
          </div>
          <div style="width:25%">
            <span>无数据显示内容</span><br>
            <Input style="margin-top:10px" v-model="tableConfig.noDataText"/>
          </div>
        </div>
      </div>
      <div class="tips" style="margin-top:10px">本项目ui基于iview ui。</div>
      <div v-show="codeShowFlag" style="margin-top:10px;text-align:right">
        <Button @click="flushCode()">刷新</Button>
        <Button type="primary" data-clipboard-action="copy"
        :data-clipboard-text="tableCode + '\n<script>\n  ' +tableCodeJs+ '\n</script>\n<style scoped>\n</style>'" class="codeBtn" @click="copy">复制</Button>
      </div>
      <pre v-highlight v-if="codeShowFlag">
        <code style="white-space: break-spaces;word-break: break-all;">
          {{tableCode}}
          {{"&lt;script&gt;"}}
          {{tableCodeJs}}
          {{"&lt;/script&gt;"}}
          {{"&lt;style scoped&gt;"}}
          {{"&lt;/style&gt;"}}
          <!-- <Input :value="previewCode + '\n<script>\n  ' +previewJSCode+ '\n</script>\n<style scoped>\n</style>'"
          type="textarea" autosize readonly/> -->
        </code>
      </pre>
      <div v-else style="padding:50px 0">
        <empty msg="正在刷新"/>
      </div>
    </div>
</template>

<script>
import Clipboard from 'clipboard'
import FIELDATTR from './FieldTableAttr.vue'
import CodeEdit from '../form_component/CodeEdit.vue'
export default {
  name: 'TableView',
  props: {
    row: {
      type: Array,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: []
    },
    codeShow: {
      type: Boolean,
      default: false
    },
    // 表头数据
    thFields: [],
    // slot配置数据
    slotAttr: {}
  },
  watch: {
    'row': {
      handler: function (e) {
        this.rows = e
        this.groupField()
        this.getCode()
      }
    },
    'codeShow': {
      handler: function (e) {
        this.codeChangeShow(e)
      }
    },
    'slotAttr': {
      handler: function (e) {
        this.slotConfig = e || {}
      }
    },
    'thFields': {
      handler: function (e) {
        if (e) {
          this.tableFieldCol = []
          this.tableCols = []
          e.forEach(item => {
            delete item.__id
            if (!item.hide) {
              this.tableFieldCol.push(item)
            }
            this.tableCols.push(item)
          })
        } else {
          this.tableCols = this.tableFieldCol
        }
      }
    }
  },
  components: {
    FIELDATTR,
    CodeEdit
  },
  data () {
    return {
      rows: this.row,
      formField: {},
      // 字段(表格)别名
      tableKey: {},
      // 表格key
      tableFieldCol: [],
      tableCols: [],
      // 表格data
      tableData: [],
      // 表格配置
      tableConfig: {
        // 边框
        border: true,
        // 斑马线
        stripe: false,
        // 大小
        size: 'default',
        // 空数据显示内容
        noDataText: '暂无数据',
        tableCode: '',
        tableCodeJs: '',
        // 复制组件
        clipboard: new Clipboard('.codeBtn')
      },
      codeShowFlag: false,
      // slot配置项
      slotConfig: this.slotAttr
    }
  },
  methods: {
    copy () {
    },
    thChange (ths, slot) {
      // console.log(ths)
      if (ths) {
        this.tableFieldCol = this.lseutil.arrayCopy([])
        let cols = []
        ths.forEach(item => {
          delete item.__id
          if (!item.hide) {
            cols.push(item)
          }
        })
        this.tableFieldCol = this.lseutil.arrayCopy(cols)
        this.tableCols = this.lseutil.arrayCopy(ths)
        // this.$forceUpdate()
      }
      if (slot) {
        this.slotConfig = this.lseutil.objCopy(slot)
      }
    },
    resetTH () {
      this.groupField(true)
    },
    groupField (reset) {
      this.tableCols = []
      this.tableFieldCol = []
      if (this.thFields && this.thFields.length > 0 && !reset) {
        this.thFields.forEach(item => {
          // delete item.__id
          if (!item.hide) {
            this.tableFieldCol.push(item)
          }
          this.tableCols.push(item)
        })
      } else {
        let rows = this.rows
        this.formField = this.lseutil.getGroupField(rows)
        this.tableKey = this.lseutil.getGroupFieldDatas(rows)
        // 设置表格头配置数据
        for (let key in this.tableKey) {
          this.tableFieldCol.push({
            title: this.tableKey[key][1],
            key: key,
            slot: '',
            type: 'String',
            align: 'left',
            tooltip: true
          })
        }
        this.tableCols = this.tableFieldCol
      }
    },
    getCode () {
      let tableConfig = this.tableConfig
      let slotStr = ''
      for (const key in this.slotConfig) {
        slotStr += `
        <template slot-scope="{ row }" slot="${key}">
            <div>${this.slotConfig[key]}</div>
        </template>\n`
      }
      let tableCode = `
        <template>
          <div>
            <Table :columns="tableFieldCol"
            :data="tableData" :border="${tableConfig.border}"
            :stripe="${tableConfig.stripe}" size="${tableConfig.size}" no-data-text="${tableConfig.noDataText}"
            >
            ${slotStr}
            </Table>
            </div>
          </template>`
      this.tableCode = tableCode
      let js = `
        export default {
            name: 'TablePreview',
            data () {
              return {
                tableFieldCol: ${JSON.stringify(this.tableFieldCol)},
                tableData: []
              }
            },
            props: {},
            watch: {},
            components: {},
            methods: {},
            mounted () {},
            created () {}
        }`
      this.tableCodeJs = js
    },
    codeChangeShow (e) {
      setTimeout(() => {
        this.codeShowFlag = e
      }, 500)
    },
    flushCode () {
      this.getCode()
      this.codeShowFlag = false
      this.codeChangeShow(true)
    },
    // 保存配置
    saveThConfig () {
      this.$emit('saveThConfig', this.tableCols, this.slotConfig)
    }
  },
  created () {
    this.groupField()
    this.getCode()
    try {
      let that = this
      let cl = this.clipboard
      cl.on('success', function (e) {
        that.lseutil.msg({
          msg: '复制成功',
          type: 1
        })
        e.clearSelection()
      })
      cl.on('error', function (e) {
        that.lseutil.msg({
          msg: '复制失败',
          type: 2
        })
        e.clearSelection()
      })
    } catch (error) {
    }
  }
}
</script>

<style scoped>

</style>
